package com.zdp.rocketmq.send;

import com.zdp.rocketmq.config.JmsConfig;
import com.zdp.rocketmq.producer.ProducerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * 异步发送消息
 * 适用于要求相响应很快的消息
 * 如果不太在意相应结果可以用这种方式
 * 应用场景:
 *     对RT时间敏感，可以支持更高的并发，回调成功触发相对应的业务，
 *     比如注册成功后通知积分系统发放优惠券。
 */
@Slf4j
@RestController
public class AsyncProducerController {

    @Autowired
    private ProducerBuilder producerBuilder;

    @RequestMapping("/api/v1/async")
    public Object callback(String keys, String tag) throws RemotingException, MQClientException, InterruptedException {
        Message message = new Message(JmsConfig.GENERAL_TOPIC, tag, keys, ("hello rocketmq = " + keys).getBytes());
        producerBuilder.getProducer().send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送消息发送成功:topic:{},tags:{},body:{}", JmsConfig.GENERAL_TOPIC, tag, ("hello rocketmq = " + keys));
            }

            @Override
            public void onException(Throwable e) {
                e.printStackTrace();
                log.warn("异步发送重试发送异常消息:topic:{},tags:{},body:{}", JmsConfig.GENERAL_TOPIC, tag, ("hello rocketmq = " + keys));
                //todo 重试方法
            }
        });
        return new HashMap<>(1);
    }
}
